package com.example.demo.controller;
import com.example.demo.entity.Course;
import com.example.demo.entity.StudentCourse;
import com.example.demo.service.StudentCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/student_courses")
public class StudentCourseController {

    @Autowired
    private StudentCourseService service;

    // POST /api/student_courses/{studentId}/{courseId}
    // 学生选课
    @PostMapping("/{studentId}/{courseId}")
    public ResponseEntity<?> enrollCourse(
            @PathVariable("studentId") String studentId,
            @PathVariable("courseId") String courseId) {

        try {
            StudentCourse newEnrollment = service.enrollCourse(studentId, courseId);
            return new ResponseEntity<>(newEnrollment, HttpStatus.CREATED);
        } catch (IllegalStateException e) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage()); // 409 Conflict
        } catch (RuntimeException e) {
            // 外键约束失败等
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); // 400 Bad Request
        }
    }

    // GET /api/student_courses/student/{studentId}
    // 查询某个学生的所有选课记录
    @GetMapping("/student/{studentId}")
    public List<StudentCourse> getCoursesByStudent(@PathVariable("studentId") String studentId) {
        return service.findCoursesByStudentId(studentId);
    }

    // DELETE /api/student_courses/{id}
    // 根据选课记录ID退课/删除记录
    @DeleteMapping("/{id}")
    public ResponseEntity<?> dropCourse(@PathVariable("id") Integer id) {
        if (service.dropCourse(id)) {
            return ResponseEntity.noContent().build(); // 204 No Content
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // PUT /api/student_courses/score
    // 更新成绩（假设请求体包含 studentId, courseId 和 score）
    @PutMapping("/score")
    public ResponseEntity<?> updateScore(@RequestBody Map<String, Object> updateRequest) {
        String studentId = (String) updateRequest.get("studentId");
        String courseId = (String) updateRequest.get("courseId");
        BigDecimal score;

        try {
            // 从 Map 中获取分数，并转换为 BigDecimal
            Object scoreObj = updateRequest.get("score");
            if (scoreObj instanceof String) {
                score = new BigDecimal((String) scoreObj);
            } else if (scoreObj instanceof Number) {
                score = BigDecimal.valueOf(((Number) scoreObj).doubleValue());
            } else {
                return ResponseEntity.badRequest().body("分数格式不正确");
            }

            if (service.updateScore(studentId, courseId, score)) {
                return ResponseEntity.ok("成绩录入成功，状态已更新为 completed");
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生或课程选课记录不存在。");
            }
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body("分数必须是有效的数字格式。");
        }
    }
    @GetMapping("/enrolled")
    public ResponseEntity<List<Course>> getEnrolledCourses(
            @RequestParam String studentId,
            @RequestParam String semesterId) {
        List<Course> courses = service.findEnrolledCoursesBySemester(studentId, semesterId);
        return ResponseEntity.ok(courses);
    }
}